<template>
  <a-modal
    :title="`公告 - ${ okHidden ? '详情' : model && model.id ? '编辑' : '新增'}`"
    :ok-button-props="{ style: okHidden && { display: 'none' } }"
    :width="780"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-if="model && model.id" label="主键ID" hidden>
          <a-input v-decorator="['id', { initialValue: model.id }]" />
        </a-form-item>
        <a-form-item label="标题">
          <a-input :readOnly="okHidden" :disabled="okHidden" :maxLength="30" placeholder="请输入标题" v-decorator="['title', { initialValue: model ? model['title'] : '' }, {rules: [{required: true, message: '主题名称不能为空！' }, {max: 30, message: '最大可输入30个字符！' }]}]" />
        </a-form-item>
        <!-- <a-form-item label="关联村庄">
            <a-input :readOnly="okHidden" placeholder="" v-show="false" v-decorator="['village_ids', { initialValue: model ? model['village_ids'] : '' }, {rules: [{required: true, message: '请选择村庄！'}]}]" />
            <div style="width: 100%;border: 1px solid #333;padding: 10px;">
              <div><a-checkbox @change="onChangeAll">全选</a-checkbox></div>
              <a-checkbox :checked="item.is" v-for="(item, index) in villageList" :key="index" @change="onChangeVillage(item)">
                {{ item.village_name }}
              </a-checkbox>
            </div>
        </a-form-item> -->
        <a-form-item label="公告对象">
          <div :style="{ marginLeft: okHidden ? '10px' : '0px' }">公开（平台所有用户可见）</div>
        </a-form-item>
        <a-form-item label="封面">
          <a-input :readOnly="okHidden" placeholder="请输入封面" v-show="false" v-decorator="['image', { initialValue: model ? model['image'] : '' }, {rules: [{required: true, message: '请上传封面！'}]}]" />
          <!-- <a :href="imgsrc" target="_blank" v-show="okHidden">
            <div class="img-src" :style="{ 'background': 'url('+imgsrc+')' }"></div>
          </a> -->
          <Upload :style="{ marginLeft: okHidden ? '10px' : '0px' }" ref="uploads" :showUploadList="{ showRemoveIcon: !okHidden }" @change="setFileList" :maxLength="1"></Upload>
          <div :style="{ marginLeft: okHidden ? '10px' : '0px' }">建议尺寸x*xpx；支持jpg、jpeg、png格式，只能上传一张图片</div>
        </a-form-item>
        <a-form-item label="内容">
          <a-input :readOnly="okHidden" placeholder="内容" v-show="false" v-decorator="['content', { initialValue: model ? model['content'] : '' }, {rules: [{required: true, message: '请输入内容！'}]}]" />
          <RichText v-show="!okHidden" ref="richText" :editContent="ruleContent" @btnGetTxt="btnSetTxt" :isLimitNumber="5000"></RichText>
          <div :style="{ marginLeft: okHidden ? '10px' : '0px' }" v-show="okHidden" v-html="ruleContent" class="htm"></div>
        </a-form-item>
        <a-form-item label="发布者">
          <a-input :readOnly="okHidden" :disabled="okHidden" :maxLength="10" placeholder="请输入发布者" v-decorator="['publisher', { initialValue: model ? model['publisher'] : '' }, {rules: [{required: true, message: '发布者名称不能为空！' }, {max: 10, message: '最大可输入10个字符！' }]}]" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import RichText from '@/components/RichText/RichText'
import Upload from '@/components/Upload/Upload'
// 表单字段
const fields = ['type', 'village_ids', 'title', 'image', 'content', 'publisher']

export default {
  props: {
    villageList: {
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    okHidden: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    serveList: {
      type: Array,
      default: () => []
    }
  },
  components: {
    RichText,
    Upload
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      form: this.$form.createForm(this),
      currentLength: 0,
      ruleContent: '',
      fileList: [],
      imgsrc: '',
      ids: []
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    if (this.model) {
      // 如果有数据则显示 数据内容
      this.ruleContent = this.model.content
      // 处理选择的村列表
      // const villageIds = this.model.village_ids.split(',')
      // const villageList = this.villageList
      // for (let i = 0; i < villageList.length; i++) {
      //   for (let n = 0; n < villageIds.length; n++) {
      //     if (villageIds[n] == villageList[i]['village_id']) {
      //       villageList[i]['is'] = true
      //     }
      //   }
      // }
      // 处理主图片
      this.$nextTick(() => {
        const images = [{
            uid: 0,
            name: '1667352832756.jpg',
            status: 'done',
            url: this.model.image
        }]
        this.$refs.uploads.setInitFileList(images)
      })
    }
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
    this.form.setFieldsValue({ type: 1 })
  },
  mounted () {},
  methods: {
    setFileList (ev) {
      // 上传回调  避免被删除后找不到相关索引产生的报错
      if (ev.length > 0) {
        this.form.setFieldsValue({ image: ev[0]['url'] })
        this.imgsrc = ev[0]['url']
      } else {
        this.form.setFieldsValue({ image: '' })
        this.imgsrc = ''
      }
    },
    btnSetTxt (content) {
      this.ruleContent = content
      this.form.setFieldsValue({ content: content })
    },
    textareaChange () {
      this.form.validateFields((errors, values) => {
        this.currentLength = values.content.length
      })
    },
    onChangeVillage (ev) {
      ev.is = !ev.is
      this.ids = []
      for (let i = 0; i < this.villageList.length; i++) {
        this.$set(this.villageList[i], 'is', this.villageList[i]['is'])
        if (this.villageList[i]['is']) {
          this.ids.push(this.villageList[i].village_id)
        }
        this.form.setFieldsValue({ village_ids: this.ids.toString() })
      }
    },
    onChangeAll (ev) {
      this.ids = []
      for (let i = 0; i < this.villageList.length; i++) {
        this.$set(this.villageList[i], 'is', ev.target.checked)
        if (ev.target.checked) {
          this.ids.push(this.villageList[i].village_id)
        }
        this.form.setFieldsValue({ village_ids: this.ids.toString() })
      }
    }
  }
}
</script>

<style>
  .img-src{
    background-size: 100% 100% !important;
    width: 120px;
    height: 120px;
  }
  .htm {
    min-height: 40px;
    max-height: 350px;
    overflow-y: scroll;
    width: 100%;
    border: 1px solid #eee
  }
</style>
